﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using 充电桩上位机.Model.PTAConfig;
using System.ComponentModel.DataAnnotations;

namespace 充电桩上位机.Model.PEM;

public class PEMModel
{
    public async Task<X509Certificate2> PEMModelReget(string pemFileDataContext)
    {
        //根据路径拿取内容
        // 读取PEM文件内容

        // 去掉PEM文件中的头部和尾部，保留Base64内容
        string publicKeyBase64 = pemFileDataContext
            .Replace("-----BEGIN CERTIFICATE-----", "")
            .Replace("-----END CERTIFICATE-----", "")
            .Replace("\n", "")
            .Replace("\r", "");
        // 将Base64字符串转换为字节数组
        byte[] publicKeyBytes = Convert.FromBase64String(publicKeyBase64);
        // 使用X509Certificate2类加载证书
        X509Certificate2 certificate = new (publicKeyBytes);

        // 打印证书的一些信息
        //Console.WriteLine("证书主题: " + certificate.Subject);
        //Console.WriteLine("证书发行者: " + certificate.Issuer);
        //Console.WriteLine("证书有效期开始: " + certificate.NotBefore);
        //Console.WriteLine("证书有效期结束: " + certificate.NotAfter);
        //Console.WriteLine("证书序列号: " + certificate.SerialNumber);

        return certificate;
    }

    public static ushort[] PEMModelSet(string pemFilePath)
    {
        try
        {
            string pemContent = File.ReadAllText(pemFilePath);

            // 去掉PEM文件中的头部和尾部，保留Base64内容
            string publicKeyBase64 = pemContent
                .Replace("-----BEGIN CERTIFICATE-----", "")
                .Replace("-----END CERTIFICATE-----", "")
                .Replace("\n", "")
                .Replace("\r", "");

            // 将Base64字符串转换为字节数组

            publicKeyBase64 = 1500 > publicKeyBase64.Length ? publicKeyBase64.PadRight(1500, '\0') : publicKeyBase64;
            return StrignToUShort(publicKeyBase64, 1500, false);
        }
        catch
        {
            return null;
        }
        
    }
    public static ushort[] StrignToUShort(string data, int length, bool jshu)
    {
        byte[] bytereg = Encoding.ASCII.GetBytes(data);
        int pick;
        if (bytereg.Length % 2 != 0)
            pick = 1;
        else
            pick = 0;

        for (int i = 0; i < length - pick; i += 2)
        {
            byte temp = bytereg[i];
            bytereg[i] = bytereg[i + 1];
            bytereg[i + 1] = temp;
        }
        ushort[] regs = new ushort[length];
        Buffer.BlockCopy(bytereg, 0, regs, 0, data.Length);

        return regs;
    }
}
